<template>
	<div>
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="900px"
			@close="closeDialog"
			:dialogFooterBtn="true"
		>
			<el-form ref="SignInDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
				<el-form-item label="活动名称" prop="activityName" :rules="{ required: true, message: '活动名称不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.activityName" placeholder="请输入活动名称" clearable></el-input>
				</el-form-item>

				<el-form-item label="活动时间" prop="activityTime" :rules="{ required: true, message: '活动时间不能为空', trigger: 'blue' }">
					<el-date-picker
						v-model="state.ruleForm.activityTime"
						type="datetimerange"
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
					/>
				</el-form-item>

				<el-form-item label="日签奖励" prop="daysSigninScore" :rules="{ required: true, message: '日签奖励积分不能为空', trigger: 'blue' }">
					<el-row :gutter="10">
						<el-col :xs="24" :sm="10" :md="10" :lg="10" :xl="10"> 每日签到固定积分</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-input v-model="state.ruleForm.daysSigninScore" placeholder="请输入日签奖励" clearable type="number" min="1">
								<template #append> 积分</template>
							</el-input>
						</el-col>
					</el-row>
				</el-form-item>

				<el-form-item label="递增签到" prop="daysIncSiginin">
					<el-switch
						v-model="state.ruleForm.daysIncSiginin"
						inline-prompt
						active-text="开启"
						inactive-text="不开启"
						:active-value="1"
						:inactive-value="0"
					/>
				</el-form-item>
				<el-form-item v-if="state.ruleForm.daysIncSiginin == 1">
					<div class="acitivty-rule">
						<!-- <el-form label-position="left"> -->
						<div class="activity-rule-content">
							<el-form-item label="次日起递增奖励" label-width="120px">
								<el-row :gutter="5">
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<el-form-item
											prop="daysIncSigninContent.integral"
											:rules="{ required: true, message: '次日起递增奖励积分不能为空', trigger: 'blue' }"
										>
											<el-input v-model="state.ruleForm.daysIncSigninContent.integral" type="number" min="1">
												<template #append>
													<div>积分</div>
												</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<el-form-item
											label="至"
											prop="daysIncSigninContent.days"
											:rules="{ required: true, message: '次日起递增奖励至多少天不能为空', trigger: 'blue' }"
										>
											<el-input v-model="state.ruleForm.daysIncSigninContent.days" type="number" min="1">
												<template #append>天</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<div class="exec-width">后不再递增</div>
									</el-col>
								</el-row>
							</el-form-item>
						</div>
						<!-- </el-form> -->
					</div>
				</el-form-item>
				<el-form-item label="连续签到" prop="daysConSignin">
					<el-switch
						v-model="state.ruleForm.daysConSignin"
						inline-prompt
						active-text="开启"
						inactive-text="不开启"
						:active-value="1"
						:inactive-value="0"
					/>
				</el-form-item>

				<el-form-item v-if="state.ruleForm.daysConSignin == 1">
					<div class="acitivty-rule">
						<!-- <el-form label-position="left"> -->
						<div class="activity-rule-content">
							<el-form-item label="条件1" label-width="50px">
								<el-row :gutter="5">
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<el-form-item
											label="连续签到"
											prop="daysConSigninContent.days"
											:rules="{ required: true, message: '连续签到多少天不能为空', trigger: 'blue' }"
										>
											<el-input v-model="state.ruleForm.daysConSigninContent.days" type="number" min="1">
												<template #append>
													<div>天</div>
												</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<el-form-item
											label="赠送积分"
											prop="daysConSigninContent.integral"
											:rules="{ required: true, message: '连续签到赠送积分不能为空', trigger: 'blue' }"
										>
											<el-input v-model="state.ruleForm.daysConSigninContent.integral" type="number" min="1">
												<template #append> 积分</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<div class="exec-width"></div>
									</el-col>
								</el-row>
							</el-form-item>
						</div>

						<div class="activity-rule-content" v-for="(item, index) in state.ruleForm.daysConSigninContents">
							<el-form-item :label="'条件' + (index + 2)" label-width="50px">
								<el-row :gutter="5">
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<el-form-item
											label="连续签到"
											:rules="{ required: true, message: '连续签到天数不能为空', trigger: 'blue' }"
											:prop="'daysConSigninContents.' + index + '.days'"
										>
											<el-input v-model="item.days" type="number" min="1">
												<template #append>
													<div>天</div>
												</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<el-form-item
											label="赠送积分"
											label-position="right"
											:rules="{ required: true, message: '连续签到赠送积分不能为空', trigger: 'blue' }"
											:prop="'daysConSigninContents.' + index + '.integral'"
										>
											<el-input v-model="item.integral" type="number" min="1">
												<template #append> 积分</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<div class="exec-width">
											<el-button type="danger" link @click="deleteByDaysConSigninContentIndex(index)"> 删除</el-button>
										</div>
									</el-col>
								</el-row>
							</el-form-item>
						</div>
						<!-- </el-form> -->
						<el-button type="primary" link @click="addDaysConSigninContent"> +添加连续签到天数</el-button>
					</div>
				</el-form-item>

				<el-form-item label="补签设置" prop="daysReSignin">
					<el-switch
						v-model="state.ruleForm.daysReSignin"
						inline-prompt
						active-text="开启"
						inactive-text="不开启"
						:active-value="1"
						:inactive-value="0"
					/>
				</el-form-item>

				<el-form-item v-if="state.ruleForm.daysReSignin == 1" label-width="50px">
					<div class="acitivty-rule">
						<div class="activity-rule-content">
							<el-form-item label="用户在">
								<el-row :gutter="5">
									<el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">
										<el-form-item prop="daysReSigninContent.days" :rules="{ required: true, message: '用户补签多少天内不能为空', trigger: 'blue' }">
											<el-input v-model="state.ruleForm.daysReSigninContent.days" type="number" min="1">
												<template #append>
													<div>天</div>
												</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<el-form-item
											label="内可补签"
											prop="daysReSigninContent.reDays"
											:rules="{ required: true, message: '用户补签多少天不能为空', trigger: 'blue' }"
										>
											<el-input v-model="state.ruleForm.daysReSigninContent.reDays" type="number" min="1">
												<template #append>天</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
										<el-form-item
											label="每次补签消耗积分"
											label-width="150px"
											prop="daysReSigninContent.reIntegral"
											:rules="{ required: true, message: '用户补签消耗积分不能为空', trigger: 'blue' }"
										>
											<el-input v-model="state.ruleForm.daysReSigninContent.reIntegral" type="number" min="1" clearable>
												<template #append>积分</template>
											</el-input>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form-item>
						</div>
						<!-- </el-form> -->
					</div>
				</el-form-item>

				<!-- </el-col> -->
				<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20"> -->
				<el-form-item label="活动说明" prop="activityDesc">
					<el-input v-model="state.ruleForm.activityDescTitle" placeholder="请选择活动说明">
						<template #append>
							<div class="cursor-pointer" @click="openRichTextDialog">选择活动说明</div>
						</template>
					</el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(SignInDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
			<!-- </el-dialog> -->
		</CustomDialog>
		<ChoiceRichTextDialog ref="ChoiceRichTextDialogRef" @choice="choiceRichText"></ChoiceRichTextDialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { type FormInstance, type FormRules } from 'element-plus';
import msg from '/@/utils/messageUtils';
import { SignInApi } from '/@/api/shop/signin';
const ChoiceRichTextDialog = defineAsyncComponent(() => import('/@/views/shop/data/richtext/choice/index.vue'));
const ChoiceRichTextDialogRef = ref();
import _ from 'lodash';
import { Session } from '/@/utils/storage';
import commonFunction from '/@/utils/commonFunction';
const { randomText } = commonFunction();
const SignInDialogFormRef = ref();
const emit = defineEmits(['refresh']);
const state = reactive({
	ruleForm: {
		id: '',
		activityTime: [],
		activityName: '',
		startTime: '',
		endTime: '',
		daysSigninScore: 0,
		daysIncSiginin: 0,
		daysIncSigninContent: {
			integral: 0,
			days: 0,
		},
		daysConSignin: 0,
		daysConSigninContent: {
			integral: 0,
			days: 0,
		},
		daysReSignin: 0,
		daysReSigninContent: {
			days: 0,
			reDays: 0,
			reIntegral: 0,
		},
		activityType: 1,
		activityDescId: '',
		activityDescTitle: '',
		daysConSigninContents: [] as any,
	},

	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

const rules = reactive<FormRules>({
	activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
	activityTime: [{ required: true, message: '请选择活动时间 ', trigger: 'blur' }],
});

const onCancel = () => {
	closeDialog();
};

const openRichTextDialog = () => {
	ChoiceRichTextDialogRef.value.openDialog();
};

const choiceRichText = (choiceRichText: ChoiceRichText) => {
	console.log('choiceRichText: ', choiceRichText);
	state.ruleForm.activityDescId = choiceRichText.id;
	state.ruleForm.activityDescTitle = choiceRichText.title;
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
	clearArraysContent();
	// state.ruleForm.activityName = '';
	// state.ruleForm.activityTime = [];
	clearIdempotent();
};

const deleteByDaysConSigninContentIndex = (index: number) => {
	state.ruleForm.daysConSigninContents.splice(index, 1);
};

const addDaysConSigninContent = () => {
	state.ruleForm.daysConSigninContents.push({
		integral: 0,
		days: 0,
	});
};

const onSubmit = async (formEl: FormInstance | undefined) => {
	const activityTime = state.ruleForm.activityTime;
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			try {
				let daysConSigninContents = _.cloneDeep(state.ruleForm.daysConSigninContents);
				// daysConSigninContents.push(state.ruleForm.daysConSigninContent);
				daysConSigninContents.splice(0, 0, state.ruleForm.daysConSigninContent);
				if (state.dialog.type === 'add') {
					await SignInApi().create({
						activityName: state.ruleForm.activityName,
						activityStartTime: activityTime[0].getTime(),
						activityEndTime: activityTime[1].getTime(),
						daysSigninScore: state.ruleForm.daysSigninScore,
						daysIncSiginin: state.ruleForm.daysIncSiginin,
						daysIncSigninContent: state.ruleForm.daysIncSigninContent,
						daysConSignin: state.ruleForm.daysConSignin,
						daysConSigninContents: daysConSigninContents,
						daysReSignin: state.ruleForm.daysReSignin,
						daysReSigninContent: state.ruleForm.daysReSigninContent,
						activityDescId: state.ruleForm.activityDescId,
						activityDescTitle: state.ruleForm.activityDescTitle,
					});
				} else {
					await SignInApi().update({
						id: state.ruleForm.id,
						activityName: state.ruleForm.activityName,
						activityStartTime: resolveTime(activityTime[0]),
						activityEndTime: resolveTime(activityTime[1]),
						daysSigninScore: state.ruleForm.daysSigninScore,
						daysIncSiginin: state.ruleForm.daysIncSiginin,
						daysIncSigninContent: state.ruleForm.daysIncSigninContent,
						daysConSignin: state.ruleForm.daysConSignin,
						daysConSigninContents: daysConSigninContents,
						daysReSignin: state.ruleForm.daysReSignin,
						daysReSigninContent: state.ruleForm.daysReSigninContent,
						activityDescId: state.ruleForm.activityDescId,
						activityDescTitle: state.ruleForm.activityDescTitle,
					});
				}
				msg().success('操作成功');
				closeDialog();
				emit('refresh');
			} catch (e) {
				console.log('e: ', e);
				msg().error('操作失败');
			} finally {
				clearIdempotent();
			}
		}
	});
};

const setIdempotent = () => {
	Session.set('idempotent', randomText(32));
};

const clearIdempotent = () => {
	Session.remove('idempotent');
};

const openDialog = async (type: string, id: string) => {
	if (type === 'edit') {
		state.dialog.title = '修改签到活动';
		state.dialog.submitTxt = '修 改';
		state.dialog.type = 'edit';
		state.ruleForm.id = id;
		const { data } = await SignInApi().view(id);
		state.ruleForm.id = id;
		state.ruleForm.activityName = data.activityName;
		state.ruleForm.activityTime = [data.activityStartTime, data.activityEndTime];
		state.ruleForm.daysSigninScore = data.daysSigninScore;
		state.ruleForm.daysIncSiginin = data.daysIncSiginin;
		state.ruleForm.daysIncSigninContent = data.daysIncSigninContentVO;
		state.ruleForm.daysConSignin = data.daysConSignin;
		state.ruleForm.daysConSigninContent = data.daysConSigninContentVOS[0];
		if (data.daysConSigninContentVOS.length > 1) {
			for (let i = 1; i < data.daysConSigninContentVOS.length; i++) {
				state.ruleForm.daysConSigninContents.push(data.daysConSigninContentVOS[i]);
			}
		}
		state.ruleForm.daysReSignin = data.daysReSignin;
		state.ruleForm.daysReSigninContent = data.daysReSigninContentVO;
		state.ruleForm.activityDescId = data.activityDescId;
		state.ruleForm.activityDescTitle = data.activityDescTitle;
	} else {
		setIdempotent();
		state.dialog.title = '新增签到活动';
		state.dialog.submitTxt = '新 增';
		state.dialog.type = type;
		// nextTick(() => {
		// 	discountDialogFormRef.value.resetFields();
		// 	discountDialogFormRef.value.clearValidate();
		// });
		state.ruleForm.activityName = '';
		state.ruleForm.activityTime = [];
	}
	state.dialog.isShowDialog = true;
};

const resolveTime = (time: any) => {
	const contentType = typeof time;

	if (contentType == 'string') {
		console.log('time: ', time, ' is string');
		return new Date(time).getTime();
	}
	return time.getTime();
};

const clearArraysContent = () => {
	SignInDialogFormRef.value.resetFields();
	state.ruleForm.daysSigninScore = 0;
	state.ruleForm.daysIncSiginin = 0;
	state.ruleForm.daysConSignin = 0;
	state.ruleForm.daysReSignin = 0;
	state.ruleForm.daysIncSigninContent = { integral: 0, days: 0 };
	state.ruleForm.daysConSigninContent = { integral: 0, days: 0 };
	state.ruleForm.daysReSigninContent = { days: 0, reDays: 0, reIntegral: 0 };
	state.ruleForm.daysConSigninContents = [];
};
defineExpose({ openDialog });
</script>

<style scoped>
.item-content {
	width: 400px;
}

.exec-width {
	width: 250px;
	margin-left: 10px;
}

.item-header {
	background-color: rgba(223, 230, 233, 1);
}

.item-body {
	margin-top: 10px;
}

.content {
	flex: 1;
}

.oper {
	width: 60px;
}

.goods-img {
	width: 50px;
	height: 50px;
}

.goods-content {
	margin-left: 10px;
	flex: 1;

	.goods-title {
		font-size: 14px;
		height: 20px;
		line-height: 20px;
		overflow: hidden;
		text-overflow: ellipsis;
		/* white-space: nowrap; */
		/* text-overflow: ellipsis; */
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
		padding-right: 5px;
	}

	.goods-price {
		font-size: 12px;
		height: 20px;
		line-height: 40px;
		color: rgba(255, 118, 117, 1);
	}
}
</style>
